package com.twu.biblioteca;

import java.io.*;
import java.util.List;
import java.util.Map;

public class Biblioteca {
    String welcomeMessage;
    PrintStream printStream;
    BufferedReader bufferedReader;
    List<LibraryBook> bookList;
    Map<String, String> options;

    public Biblioteca(PrintStream printStream, String welcomeMessage, List<LibraryBook> bookList, Map<String, String> options,
                      BufferedReader bufferedReader) {
        this.welcomeMessage = welcomeMessage;
        this.printStream = printStream;
        this.bookList = bookList;
        this.options = options;
        this.bufferedReader = bufferedReader;
    }

    public void run(){
        displayWelcomeMessage();
        listBooks();
        displayOptions();
        try {
            executeUserChoice(getUserOptionChoice());
        } catch (IOException e) {
            printStream.println("Error Reading Input");
        }
    }

    public void displayWelcomeMessage() {
        printStream.println(welcomeMessage);
    }

    public void listBooks() {
        for (LibraryBook book : bookList) {
            printStream.println(book.toString());
        }
    }

    public void displayOptions() {
        for(String option : options.values())
            printStream.println(option);
    }

    public String getUserOptionChoice() throws IOException {
        return bufferedReader.readLine();
    }

    public void executeUserChoice(String userChoice) throws IOException {

        if(!isValid(userChoice)){
            printStream.println("Select a valid option!");
            getUserOptionChoice();
        }
        if(userChoice.equals("1"))
            listBooks();
        if(userChoice.equals("2")){
            promptUserForBookSelection();
            checkOut(stringToBook(getUserOptionChoice()));
        }

    }

    private boolean isValid(String userChoice) {
        for(String validOption : options.keySet())
            if (userChoice.equals(validOption))
                return true;
        return false;
    }

    private void promptUserForBookSelection(){
        printStream.println("What book would you like to check out?");

    }

    public void checkOut(LibraryBook book) {
        book.setAvailability(false);
        printStream.println("Thank you. Enjoy the book!");
    }

    public LibraryBook stringToBook(String stringInput) {
        LibraryBook book = new LibraryBook(stringInput);
        return book;
    }
}
